/**
 * Created by rongyao on 2017/10/31.
 */
var mongoose = require('mongoose');
var multer  = require('multer');
var path  = require('path');
var async = require('async');
const DataModel = require('../models/upload.model');
const Comment = require('../models/comment.model');


var storage = multer.diskStorage({
	destination: function (req, file, cb) {
		cb(null, './uploads')
	},
	filename: function (req, file, cb) {
		//返回一个文件名，该文件名是通过表单文件上传的文件名称（前台设置avatar）+时间戳+原始文件的扩展名
		cb(null, file.fieldname + '-' + Date.now()+path.extname(file.originalname))
	}
})
exports.upload = function (req,res,next) {
	//实例化multer
	var upload = multer({
		storage:storage
	}).single('avatar');
	
	upload(req,res,function(err){
		req.file.cateId = req.params.cateId
		const  dataModel = new DataModel(req.file);
		
		// console.log(req.body);
		
		// console.log(dataModel);
		dataModel.save()
			.then(data=>{
				res.json(data);
			})
		res.end('File is uploaded');
	});
}





exports.remove = function (req,res,next) {
	const id = req.params.id;
	DataModel.findByIdAndRemove(id,function (err,data) {
		res.json(data);
	})
}

//分页查询
exports.list = function (req,res,next) {
	var page = (req.body.page)?req.body.page:1;
	var rows = (req.body.rows)?req.body.rows:10;
	// console.log(rows);
	var queryCondition={}//查询条件
	//cateId 要精确搜索
	if(req.body.cateId && req.body.cateId.length>0){
		console.log(req.body);
		cateId = JSON.parse(req.body.cateId);
		// console.log(cateId);
		var cateIds = [];
		for(var i=0;i<cateId.length;i++){
			cateIds.push(mongoose.Types.ObjectId(cateId[i]));
		}
		console.log(cateIds);
		// console.log(cateIds);
		queryCondition={cateId: {$in:cateIds}}
	}
	
	// console.log(queryCondition);
	// console.log(queryCondition)
	// console.log({page:page,limit:limit});
	DataModel.paginate(queryCondition, {sort: { _id: -1 }, page: parseInt(page), limit: parseInt(rows) }, function(err, result) {
			result.rows = result.docs;
			delete result.docs;
			res.json(result);
		});
	
}

//删除多个
exports.deletes = function (req,res,next) {
	var ids = req.body.ids; //字符串
	console.log(ids.split(',').length>0);
	if(ids.length>0){
		DataModel.remove({_id:{$in:ids.split(',')}})
			.then(data=>{
				res.json({"msg":"deletes success","status":200});
			})
	}else{
		res.json({"msg":"deletes fail","status":404});
	}
}

